package 二叉树练习题;

import java.util.LinkedList;
import java.util.Queue;

public class C如何从顶部开始逐层打印二叉树结点数据 {

    public static void printTreeLayer(BiTNode root) {
        if (root == null) {
            return;
        }
        BiTNode p;

        Queue<BiTNode> queue = new LinkedList<>();
        queue.offer(root);

        while (queue.size() > 0) {
            p = queue.poll();
            System.out.print(p.data + " ");
            if (p.lchild != null) {
                queue.offer(p.lchild);
            }
            if (p.rchild != null) {
                queue.offer(p.rchild);
            }
        }
    }

    public static BiTNode arraytotree(int[] arr, int start, int end) {
        BiTNode root = null;
        if (end >= start) {
            root = new BiTNode();
            int mid = (start + end + 1) / 2;
            root.data = arr[mid];
            root.lchild = arraytotree(arr, start, mid - 1);
            root.rchild = arraytotree(arr, mid + 1, end);
        } else {
            root = null;
        }
        return root;
    }

    public static void main(String[] args) {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        BiTNode root;
        root = arraytotree(arr, 0, arr.length - 1);
        System.out.print("树的层序遍历结果为：");
        printTreeLayer(root);
    }
}
